#include "../renderer/renderer.h"
#include "../game/game.h"
#include "../ui/ui.h"

#include "cl_input.h"
#include "client.h"
#include <SDL/SDL.h>

int locked_x;
int locked_y;

#define MARGIN 60
static void set_camera(player_t * p)
{
	//根据鼠标指针位置调整camera
#if 0
	if (mouse_pos_x < 10)
		rd.camera.x -= 20;
	if (mouse_pos_y < 10)
		rd.camera.y -= 20;
	if (mouse_pos_x > rd.camera.w - 10)
		rd.camera.x += 20;
	if (mouse_pos_y > rd.camera.h - 10)
		rd.camera.y += 20;
#endif
#if 0
	if (mouse_pos_x <= 1
	  ||mouse_pos_y <= 1
	  ||mouse_pos_x >= rd.camera.w-1
	  ||mouse_pos_y >= rd.camera.h-1)
	{
		rd.camera.x += 3*mouse_rel_x;
		rd.camera.y += 3*mouse_rel_y;
	}
#endif

	if (rd.camera_locked) {
		rd.camera.x = p->x - locked_x;
		rd.camera.y = p->y - locked_y;
	} else {
		if (mouse_pos_x <= 1)
			rd.camera.x += 3*mouse_rel_x;
		if (mouse_pos_y <= 1)
			rd.camera.y += 3*mouse_rel_y;
		if (mouse_pos_x >= rd.camera.w-1)
			rd.camera.x += 3*mouse_rel_x;
		if (mouse_pos_y >= rd.camera.h-1)
			rd.camera.y += 3*mouse_rel_y;
	}

	//让p在屏幕中间
	if (key_str_is_down("SPACE")) {
		rd.camera.x = p->x - 0.5*rd.camera.w;
		rd.camera.y = p->y - 0.5*rd.camera.h;
	}

	//限定p在camera内,且内边距为MARGIN
	if (rd.camera.x > (p->x - MARGIN))
		rd.camera.x = p->x - MARGIN;
	if (rd.camera.y > (p->y - MARGIN))
		rd.camera.y = p->y - MARGIN;
	if (rd.camera.x < (p->x + p->w + MARGIN - rd.camera.w))
		rd.camera.x = p->x + p->w + MARGIN - rd.camera.w;
	if (rd.camera.y < (p->y + p->h + MARGIN - rd.camera.h))
		rd.camera.y = p->y + p->h + MARGIN - rd.camera.h;

	//限定camera在地图内
	if (rd.camera.x < 0)
		rd.camera.x = 0;
	if (rd.camera.y < 0)
		rd.camera.y = 0;
	if (rd.camera.x > rd.map.w - rd.camera.w)
		rd.camera.x = rd.map.w - rd.camera.w;
	if (rd.camera.y > rd.map.h - rd.camera.h)
		rd.camera.y = rd.map.h - rd.camera.h;

	locked_x = p->x - rd.camera.x;
	locked_y = p->y - rd.camera.y;
}

static void show_world(void)
{
	rd_show_map();
}

static void show_players(void)
{
	player_t * p = &game.player[0];

	//人物阴影效果
	rd_apply_surface(p->x - rd.camera.x, p->y - rd.camera.y, rd.shadow, rd.screen, NULL);

	rd_apply_surface(p->x - rd.camera.x, p->y - rd.camera.y, p->model->sprite[p->state],
			rd.screen, rd_model_clip(p->model, p->direction, p->frame));

	//视野限制
	/*rd_apply_surface(p->x - rd.camera.x - 0.5*(rd.sight_mask->w - p->w),
			p->y - rd.camera.y - 0.5*(rd.sight_mask->h - p->h),
			rd.sight_mask, rd.screen, NULL);*/
}

static void show_units(void)
{
	;
}

void cl_display(void)
{
	set_camera(&game.player[0]);

	show_world();
	show_players();
	show_units();
	show_ui();

	//显示指针
	rd_apply_surface(mouse_pos_x, mouse_pos_y, rd.cursor_img, rd.screen, NULL);
	//显示调试信息
	rd_apply_surface(50, 50, rd.debug, rd.screen, NULL);

	rd_show_all();
}

